
const reg = /(?=(\B)(\d{3})+$)/g

Page({
  data: {
    userInfo: '',
    balanceFormat: '', // U米
    bIsShowModal: false,
    bIsAutofocus: false,
    createStatus: '1', // 0为未创建， 1已创建， 3创建中
    onePassword: '',
    twoPassword: '',
  },
  onLoad() {
    this.setData({ userInfo: wx.getStorageSync('userInfo') })
    this.getBalance()
  },
  /**
   * @see 获取U米及是否已创建账号
   */
  getBalance() {
    wx.showNavigationBarLoading()
    wx.$API['person/getBalance']({}).then((result) => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
      const { balance, createStatus } = result
      this.setData({
        balanceFormat: balance.replace(reg, ','),
        createStatus
      })
    }).catch((err) => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
      wx.showToast({
        title: err,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * @see 创建账号获取U米
   */
  createBlockAccount() {
    const request = { payPassword: this.data.twoPassword }
    wx.showLoading({
      title: '正在生成U米账号，请耐心稍等...',
      mask: true
    })
    wx.$API['person/createBlockAccount'](request).then((result) => {
      wx.hideLoading()
      this.setData({ createStatus: '3', bIsShowModal: false })
      this.getBalance()
    }).catch((err) => {
      wx.showToast({
        title: err,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * @see 显示设置支付密码弹窗
   */
  showModal() {
    this.setData({
      bIsShowModal: true,
      bIsAutofocus: true
    })
  },
  /**
   * @see 支付密码弹窗确认触发
   */
  handleCloseModal () {
    const { onePassword, twoPassword } = this.data
    if (onePassword !== twoPassword || !onePassword || onePassword.length !== 6) {
      wx.showToast({
        title: '请输入相同的六位数密码',
        icon: 'none',
        duration: 2000
      })
      return
    }
    this.createBlockAccount()
  },
  /**
   * @see 取消输入
   */
  handleCancel() {
    setTimeout(() => {
      this.setData({ bIsShowModal: false, bIsAutofocus: false })
    }, 300)
  },
  changeOnePassword(e) {
    this.setData({ onePassword: e.detail.detail.value })
  },
  changeTwoPassword(e) {
    this.setData({ twoPassword: e.detail.detail.value })
  },
  /**
   * @see 下拉刷新
   */
  onPullDownRefresh() {
    this.getBalance()
  }
})